package com.lvzero.answer.util;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

/**
 * 获取中奖概率的工具类
 * 来自网络
 */
public class AwardUtil {

    /**
     * 获取的是奖品的index
     * @param map
     * @return
     */
    public static int getIndex(List<Map> map) {

        int random = -1;

        try {
            //计算总权重
            double sumWeight = 0;
            for (int i = 0; i < map.size(); i++) {
                int weight = (int) map.get(i).get("weight");
                sumWeight += weight;
            }

            //产生随机数

            //产生随机数
            double randomNumber;
            randomNumber = Math.random();

            //根据随机数在所有奖品分布的区域并确定所抽奖品
            double d1 = 0;
            double d2 = 0;
            for (int i = 0; i < map.size(); i++) {
                d2 += Double.parseDouble(String.valueOf(map.get(i).get("weight"))) / sumWeight;
                if (i == 0) {
                    d1 = 0;
                } else {
                    d1 += Double.parseDouble(String.valueOf(map.get(i - 1).get("weight"))) / sumWeight;
                }
                if (randomNumber >= d1 && randomNumber <= d2) {
                    random = i;
                    break;
                }
            }


        } catch (Exception ex) {
            System.out.println("生成抽奖随机数出错，出错原因：" + ex.getMessage());
        }
        return random;
    }
}
